#!/usr/bin/perl -w
use strict;
use v5.14;
use utf8;

use Data::Dumper;
use Encode;
use Net::LDAP;
use Config::Simple;
binmode(STDOUT, ":encoding(UTF-8)");
binmode(STDIN, ":encoding(UTF-8)");
binmode(STDERR, ":encoding(UTF-8)");

sub gen_gid {
  my $conn = shift @_;
  my $gid = 0;
  my $msg = $conn->search(base => 'cn=max_gid_number,dc=jhc,dc=cn',
			  scope => 'base',
			  filter => '(objectClass=*)',
			  callback => sub {
			    my ($result,$entry) = @_;
			    $result->code && say $result->error;
			    if ($entry) {
			      $gid = $entry->get_value('gidNumber');
			      $entry->replace(gidNumber => $gid+1);
			      $entry->update($conn);
			    }
			  }
			 );
  $gid
}

#新生班级名可先想法抽出，再用下面的命令来做：
#cat ~/names.csv | awk -F',' '{print $3;}' | sort | uniq |xargs -n 1 ./add_class.pl
my $USAGE = "用法： ./add_class.pl 班级名 学院名";
(@ARGV < 1 || @ARGV > 2) && die $USAGE;
my ($classname,$institute) = @ARGV;
$institute || ($institute = 'info');
#say $classname . ',' . $institute;

my $cfg = new Config::Simple($ENV{'HOME'} . '/.ldapconf');
#$cfg->param('binddn');
my $ldap = Net::LDAP->new($cfg->param('host'));
$ldap->bind($cfg->param('binddn'), password => $cfg->param('password'));

my $gid = gen_gid($ldap);
my $classdn = "cn=${classname},ou=${institute},ou=groups,dc=jhc,dc=cn";
$ldap->add(
	   $classdn,
	   attrs => [
		     cn          => $classname,
		     gidNumber   => $gid,
		     objectClass => [qw /top posixGroup/],
		]
	  );
say decode("utf8","$classdn added.");
$ldap->unbind;

